package us.icitap.timsportal.management;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

import us.icitap.timsportal.ejb.PortalBeanLocal;
import us.icitap.timsportal.entity.Module;
import us.icitap.timsportal.entity.OrgStructure;
import us.icitap.timsportal.entity.Role;
import us.icitap.timsportal.util.SearchListener;
import us.icitap.timsportal.web.custom.PNativeButton;
import us.icitap.timsportal.web.custom.PTable;
import us.icitap.timsportal.web.custom.PTextField;
import us.icitap.timsportal.web.custom.PortalForm;
import us.icitap.timsportal.web.custom.PortalLabel;
import us.icitap.timsportal.web.custom.PortalVerticalLayout;

import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.util.BeanItem;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.Table;
import com.vaadin.ui.Table.ColumnGenerator;
import com.vaadin.ui.TextArea;

@SuppressWarnings("serial")
public class ModuleEditor extends PortalVerticalLayout {
	PortalBeanLocal portalBean;
		
	private PTable mTable;
	private BeanItemContainer<Module> mContainer;
	private OrgStrList orgStrList = new OrgStrList();
	private RoleList roleList = new RoleList();
	private Module selectedModule;
	
	private static final Object[] M_COL_ORDER = new Object[]{"moduleName", "moduleURL", "devModuleURL", "status"};
	private static final String[] M_COL_HEADER = new String[]{"Emri", "URL-Live", "URL-Dev", "Status"};
	
	private static final Object[] OS_COL_ORDER = new Object[]{"id", "name", "status"};
	private static final String[] OS_COL_HEADER = new String[]{"Id", "Emri", "Status"};
	
	private static final Object[] R_COL_ORDER = new Object[]{"id", "tag", "status"};
	private static final String[] R_COL_HEADER = new String[]{"Id", "Tag", "Status"};
	private static final List<Object> R_FORM = Arrays.asList(new Object[]{"id", "tag", "status", "description"});
	
	public ModuleEditor(List<Module> list){
		setStyleName("timsportal");
		setWidth("550px");
		setMargin(true);
		setSpacing(true);
		
		PortalLabel title = new PortalLabel("Modulet", Label.CONTENT_XHTML);
		title.setSizeFull();
		title.setStyleName("menu");
		
		mContainer = new BeanItemContainer<Module>(Module.class);
		mContainer.addAll(list);
		mTable = new PTable("", mContainer);
		mTable.setPageLength(6);
		mTable.setSizeFull();
		mTable.setSelectable(true);
		mTable.setImmediate(true);
		mTable.setVisibleColumns(M_COL_ORDER);
		mTable.setColumnHeaders(M_COL_HEADER);
		mTable.addListener(new Property.ValueChangeListener() {			
			@Override
			public void valueChange(ValueChangeEvent event) {
				Object o = event.getProperty().getValue();
				if(o==null){
					selectedModule = null;
					orgStrList.setOrgStrList(null);
					roleList.setRoleList(null);
					return;
				}
				selectedModule = (Module) o;
				orgStrList.setOrgStrList(selectedModule.getOrgStructures());
				roleList.setRoleList(selectedModule.getRoles());
			}
		});
		
		TabSheet t = new TabSheet();
		t.addTab(orgStrList, "Strukturat Organizative");
		t.addTab(roleList, "Rolet");
		
		addComponentAsFirst(title);
		addComponent(mTable);
		addComponent(t);
	}
	
	@Override
	public void attach(){
		super.attach();
		portalBean = this.getApplication().getPortalBean();
	}
	
	class OrgStrList extends PortalVerticalLayout {
		
		PTable osTable;
		BeanItemContainer<OrgStructure> osContainer;
		PNativeButton addButton;
		OrgStructureWindow osWindow;
		
		OrgStrList(){
			setSpacing(false);
			setStyleName("timsportal-without-border");
			
			osWindow = new OrgStructureWindow();
			osWindow.addSearchListener(new SearchListener<OrgStructure>() {
				@Override
				public <T> void searchFinished(T o) {
					OrgStructure os = (OrgStructure) o;
					selectedModule.getOrgStructures().add(os);
					selectedModule = portalBean.saveModule(selectedModule, null, null);
					mContainer.addBean(selectedModule);
					mTable.setValue(selectedModule);
					osContainer.removeAllItems();
					osContainer.addAll(selectedModule.getOrgStructures());
				}
			});
			
			addButton = new PNativeButton("SHTO");
			addButton.setWidth("100px");
			addButton.setEnabled(false);
			addButton.addListener(new Button.ClickListener() {				
				@Override
				public void buttonClick(ClickEvent event) {
					if(osWindow.getParent()!=null)return;
					osWindow.clear();
					getWindow().addWindow(osWindow);
					
				}
			});
			
			osContainer = new BeanItemContainer<OrgStructure>(OrgStructure.class);
			osTable = new PTable("", osContainer);
			osTable.setPageLength(6);
			osTable.setSizeFull();
			osTable.setSelectable(false);
			osTable.setVisibleColumns(OS_COL_ORDER);
			osTable.setColumnHeaders(OS_COL_HEADER);
			

			addComponent(osTable);
			addComponent(addButton);			
		}
		
		void setOrgStrList(Set<OrgStructure> list){
			osContainer.removeAllItems();
			addButton.setEnabled(selectedModule!=null);
			if(list != null)
				osContainer.addAll(list);
		}
		
	}
	
	class RoleList extends PortalVerticalLayout implements Button.ClickListener, Property.ValueChangeListener{
		PTable rTable;
		BeanItemContainer<Role> rContainer;
		PNativeButton addButton, saveButton;
		PortalForm rForm;
		Role newRole;
		boolean newMode;
		
		RoleList(){
			setSpacing(false);
			setStyleName("timsportal-without-border");
			
			rContainer = new BeanItemContainer<Role>(Role.class);
			rTable = new PTable("", rContainer);
			rTable.setPageLength(6);
			rTable.setSizeFull();
			rTable.setSelectable(true);
			rTable.setImmediate(true);
			rTable.setVisibleColumns(R_COL_ORDER);
			rTable.setColumnHeaders(R_COL_HEADER);
			rTable.addListener((Property.ValueChangeListener) this);
			rTable.addGeneratedColumn("status", new ColumnGenerator() {
				@Override
				public Object generateCell(Table source, Object itemId, Object columnId) {
					Role r = (Role) itemId;
					Label l;
					if(r.getStatus())
						l = new Label("AKTIVE");
					else l = new Label("JO-AKTIVE");
					return l;
				}
			});
			
			addButton = new PNativeButton("ROL I RI");
			addButton.setImmediate(true);
			addButton.setWidth("100px");
			addButton.addListener((Button.ClickListener) this);
			addButton.setEnabled(false);
			saveButton = new PNativeButton("RUAJ");
			saveButton.setImmediate(true);
			saveButton.setWidth("100px");
			saveButton.setEnabled(false);
			saveButton.addListener((Button.ClickListener) this);
			
			rForm = new PortalForm();
			rForm.setCaption("Roli");
			rForm.setWriteThrough(false);
			rForm.setFormFieldFactory(new DefaultFieldFactory(){
				@Override
				public Field createField(Item item, Object propertyId, Component uiContext){
					Field f = super.createField(item, propertyId, uiContext);
					if("id".equals(propertyId) || "tag".equals(propertyId)){
						PTextField pt = new PTextField(propertyId.toString());
						pt.setRequired(true);
						pt.setWidth("200px");
						pt.setNullRepresentation("");
						pt.setImmediate(true);
						return pt;
					} else if("description".equals(propertyId)){
						TextArea ta = new TextArea("Pershkrimi");
						ta.setWidth("200px");
						ta.setRows(3);
						ta.setNullRepresentation("");
						return ta;
					}	else if("status".equals(propertyId)){
						CheckBox box = new CheckBox("AKTIVE");
						return box;
					}
					return f;
				}
			});
			
			HorizontalLayout hl = new HorizontalLayout();
			hl.setSpacing(false);
			hl.addComponent(addButton);
			hl.addComponent(saveButton);
			
			addComponent(rTable);
			addComponent(hl);
			addComponent(rForm);
		}
		
		void setRoleList(Set<Role> list){
			rContainer.removeAllItems();
			rForm.setItemDataSource(null, R_FORM);
			saveButton.setEnabled(false);
			addButton.setEnabled(selectedModule!=null);
			if(list != null)
				rContainer.addAll(list);
		}

		@Override
		public void buttonClick(ClickEvent event) {
			Button b = event.getButton();
			if(b==addButton){
				newRole = new Role();
				newRole.setModule(selectedModule);
				rForm.setItemDataSource(new BeanItem<Role>(newRole), R_FORM);
				newMode = true;
				saveButton.setEnabled(true);
			}
			if(b==saveButton){
				if(!rForm.isValid())
					return;
				rForm.commit();
				if(newMode){
					rContainer.addBean(newRole);
					newMode = false;
				}
				rForm.setItemDataSource(null, R_FORM);
				saveButton.setEnabled(false);				
				selectedModule = portalBean.saveModule(selectedModule, rContainer.getItemIds(), null);
				mContainer.addBean(selectedModule);
				mTable.setValue(selectedModule);
				/**Role Table Refresh*/
				rContainer.removeAllItems();
				rContainer.addAll(selectedModule.getRoles());
			}
		}

		@Override
		public void valueChange(ValueChangeEvent event) {
			if(rTable == event.getProperty()){
				newMode = false;
				Item item = rTable.getItem(rTable.getValue());
				if(item==null){
					rForm.setItemDataSource(null, R_FORM);
					saveButton.setEnabled(false);
					return;
				}
				if(item!=rForm.getItemDataSource()){
					rForm.setItemDataSource(item, R_FORM);
					saveButton.setEnabled(true);
				}
					
//				Object o = event.getProperty().getValue();
//				if(o==null){
//					rForm.setItemDataSource(null, R_FORM);
//					saveButton.setEnabled(false);
//					return;
//				}
//				Role r = (Role) o;
//				rForm.setItemDataSource(new BeanItem<Role>(r), R_FORM);
//				saveButton.setEnabled(true);
			}			
		}
				
	}

}
